package com.surpermaket.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@Controller
public class CodeController {

    @RequestMapping("/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response){

        //request是请求
        //response是响应

        //构建验证码图片
        BufferedImage image = new BufferedImage(100,43,BufferedImage.TYPE_INT_RGB);
        //构建获取图片上下文，用于绘制图片内容
        Graphics g = image.getGraphics();
        //给图片添加背景色
        Random r = new Random();
        //给背景色添加三个随机数RGB
        Color color = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
        //使用画笔绘制出矩形。宽高比100/43
        g.fillRect(0,0,100,43);
        //4.生成验证码内容
        String code = createString(4);
        //存入session
        HttpSession session = request.getSession();
        //将验证码存入session
        session.setAttribute("scode",code);

        //5.随机颜色
        color = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
        g.setColor(color);
        //字体大小
        g.setFont(new Font("楷书",Font.ITALIC,30));
        g.drawString(code,10,36);
        //6.设置消息响应头，让浏览器以图片形式打开
        response.setContentType("image/jpeg");
        //7.设置消息响应头不缓存
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Pragma","no-cache");
        response.setDateHeader("expries",-1);
        //7,获取字节流
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image,"jpg",os);
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    //生成N个的字符，不重复，来源于数字和字母
    public String createString(int n){
        String src = "qwertyuiopasdfghjklzxcvbnm1234567890";
        //辅助数组，用于记录是否重复，这个数组相当于用来映射上方字符串的每一个下标
        boolean[] flogs = new boolean[src.length()];
        Random r = new Random();
        String result = "";

        for(int i = 0; i<n;){
            //生成一个随机的下标
            int index = r.nextInt(src.length());
            //如果这个下标的值为false
            if(!flogs[index]){
                //charAt() 方法用于返回指定索引处的字符。
                result += src.charAt(index);
                //最后再把该处索引标记为true，表示已选择
                flogs[index] = true;
                i++;
            }

        }

        return result;

    }

}
